import React from 'react';
import {Layout, Tabs, Icon} from 'antd';
import {inject, observer} from 'mobx-react';
import LayoutHome from './LayoutHome';
import {Header, Sider} from './components';
import {ToolHistory, ToolRoute} from '../utils';

import './LayoutTab.scss';

/**
 * 标签页面布局
 */
@inject('store')
@observer
export default class LayoutTab extends LayoutHome {
  constructor(props) {
    super(props);
    this.tabs = []; //标签列表
  }

  render() {
    //Layout对IE9的兼容性不好，使用要慎重
    return (
      <div className="g-layout-tab">
        <Header />
        <Layout>
          {this.renderSider()}
          {this.renderContent()}
        </Layout>
      </div>
    );
  }

  /**
   * 侧边栏
   */
  renderSider() {
    return <Sider type={this.props.type} />;
  }

  /**
   * 主体
   */
  renderContent() {
    return <Layout.Content className="content">{this.renderRoutes()}</Layout.Content>;
  }

  /**
   * 子路由页面
   */
  renderRoutes() {
    //二级子路由列表
    const {routes} = this.props;
    //当前路由信息
    const {path, label} = this.props.store.routerData || {};
    if (!path) return;

    //添加未点击的二级路由组件
    if (!this.tabs.find((item) => item.path === path)) {
      let route = routes.find((item) => item.props.path === path);
      if (!route) return;

      //生成懒加载组件
      let view = this.renderLayload(route.props.view);
      this.tabs.push({path, label, view});
    }

    //创建标签页
    let panes = this.tabs.map((item, index) => {
      return (
        <Tabs.TabPane tab={this.renderTab(item, index, path)} key={item.path}>
          {item.view}
        </Tabs.TabPane>
      );
    });

    return (
      <Tabs type="card" activeKey={path}>
        {panes}
      </Tabs>
    );
  }

  /**
   * 懒加载组件
   * @param  path 组件名：为src目录下的相对路径。
   */
  renderLayload(path) {
    let View = () => import(`@/${path}`);
    View = ToolRoute.lazyLoad(View, {path});
    return <View />;
  }

  /**
   * 标签栏
   * @param  item 组件数据
   * @param  index 组件索引
   * @param  path 当前路由地址
   */
  renderTab(item, index, path) {
    let style = {display: path === item.path ? 'none' : ''};
    let click = () => {
      this.tabs.splice(index, 1);
      this.setState({});
    };
    return (
      <span className="content-tab">
        <span onClick={() => path !== item.path && ToolHistory.href(item.path)}>{item.label}</span>
        <Icon style={style} className="icon" type="close" onClick={click} />
      </span>
    );
  }
}
